#include "cocos2d.h"
#include "Cockroach.h"
#include "SimpleAudioEngine.h"
#include "HelloWorldScene.h"
#include "JNIClass.h"
USING_NS_CC;
USING_NS_CC_EXT;

CockRoach::CockRoach(CCPoint p,float scale)
{
	initWithSpriteFrameName(kImageCockRoachFirst);

	setPosition(p);

	setLevel(1);

	setStatus(IDLE);

	setScale(scale);

	runAction(fRunning());

	oldpos = p;
	
	CCPointArray *array = CCPointArray::create(20);

	float randx = rand() % 3 + 2;

	float x = 0, y = 0; 

	array->addControlPoint(ccp(p.x, p.y));


	for(int j = 0; j < randx; j++  )
	{
		x = rand() % 320 - boundingBox().size.width/2;

		if( x <= 0 )
			x = boundingBox().size.width/2;

		y = rand() % 480 - boundingBox().size.height/2;

		array->addControlPoint(ccp(x, y));
	}

	array->addControlPoint(ccp(rand() % 320, - boundingBox().size.height / 2));

	CCCatmullRomTo* ac = CCCatmullRomTo::create(rand() % 4 + 10, array);

	array = NULL;

	CCFiniteTimeAction *seq = CCSequence::create(ac, NULL);

	runAction(seq);

	schedule(schedule_selector(CockRoach::rotate), 0.06f);

}

void CockRoach::rotate(float t)
{
	CCPoint newpos = getPosition();

	CCPoint pos1 = oldpos;

	CCPoint pos2 = newpos;

	float theta = atan((pos1.y-pos2.y)/(pos1.x-pos2.x)) * 180 * 7 /22; // 22/7 = pi

	float calculatedAngle = 0;

	if(pos1.y - pos2.y > 0)
	{
		if(pos1.x - pos2.x < 0)
		{
			calculatedAngle = (-90-theta);
		}
		else if(pos1.x - pos2.x > 0)
		{
			calculatedAngle = (90-theta);
		}       
	}
	else if(pos1.y - pos2.y < 0)
	{
		if(pos1.x - pos2.x < 0)
		{
			calculatedAngle = (270-theta);
		}
		else if(pos1.x - pos2.x > 0)
		{
			calculatedAngle = (90-theta);
		}
	}

	if (calculatedAngle < 0)
	{
		calculatedAngle+=360;
	}
	calculatedAngle += 180;

	//CCLog("angle %f", calculatedAngle);

	runAction(CCRotateTo::create(0.05f, calculatedAngle));

	oldpos = newpos;
}

float CockRoach::fRotateAngle()
{
	CCPoint newpos = getPosition();

	CCPoint pos1 = oldpos;

	CCPoint pos2 = newpos;

	float theta = atan((pos1.y-pos2.y)/(pos1.x-pos2.x)) * 180 * 7 /22; // 22/7 = pi

	float calculatedAngle = 0;

	if(pos1.y - pos2.y > 0)
	{
		if(pos1.x - pos2.x < 0)
		{
			calculatedAngle = (-90-theta);
		}
		else if(pos1.x - pos2.x > 0)
		{
			calculatedAngle = (90-theta);
		}       
	}
	else if(pos1.y - pos2.y < 0)
	{
		if(pos1.x - pos2.x < 0)
		{
			calculatedAngle = (270-theta);
		}
		else if(pos1.x - pos2.x > 0)
		{
			calculatedAngle = (90-theta);
		}
	}

	if (calculatedAngle < 0)
	{
		calculatedAngle+=360;
	}
	calculatedAngle += 180;

	//CCLog("angle %f", calculatedAngle);

	return calculatedAngle;
}


bool CockRoach::init(CCPoint p,float scale)
{
	// Get player by child tags
	// load the sprite-sheet in init() method
//	((HelloWorld*)getParent())->setState(STARTGAME);
	this->setLevel(1);
	this->setStatus(IDLE);

	// create the sprite from sprite frame name
	CCSprite *aSprite = CCSprite::createWithSpriteFrameName("chuyendonggian/congian1.png");

	// add action fRunning() hanh dong con gian chay se lap di lap lai nhieu lan

	CockRoachInit(p,scale);
	this->addChild(aSprite);
	aSprite->runAction(fRunning());
	return true;
}

void CockRoach::CockRoachInit(CCPoint p,float scale)
{
	this->setPosition(p);

	this->setScale(scale);
}

// Hoat dong bo cua con gian
CCRepeatForever * CockRoach::fRunning()
{
	int numframe = 3;
    CCArray* frames = CCArray::createWithCapacity(numframe);
    
    CCSpriteFrameCache* frameCache = CCSpriteFrameCache::sharedSpriteFrameCache();
    
    //nap 3 frame hinh vao frames
    char file[100] = {0};
	
    for (int i = 0; i < numframe; i++)
    {
        sprintf(file, "gian%d.png", i+1);

		CCSpriteFrame* frame = frameCache->spriteFrameByName(file);

        frames->addObject(frame);
    }
    
    //tao animation tu frames
    CCAnimation* animation = CCAnimation::createWithSpriteFrames(frames, 0.1);

    CCAnimate* animate = CCAnimate::create(animation);
    
    CCRepeatForever* repeat = CCRepeatForever::create(animate);

    return repeat;
}

void CockRoach::play() {
	if(this->getStatus() != RUN)
	{
		this->setStatus(RUN);
	}
}

void CockRoach::updateScore()
{
	((HelloWorld*)getParent())->fUpdateUIScore();
    //((HelloWorld*)getParent())->GameOver = true; //bi dung la GameOver
    //((HelloWorld*)getParent())->playSound(SoundHit);


	// update score to parent
	//CCLog("Update score to parent class HelloWorldScene !!!");
}

void CockRoach::updateEscape()
{
	((HelloWorld*)getParent())->setCockRoachEscape(); // Tang len 1
    //((HelloWorld*)getParent())->GameOver = true; //bi dung la GameOver
    //((HelloWorld*)getParent())->playSound(SoundHit);


	// update score to parent
	//CCLog("Update score to parent class HelloWorldScene !!!");
}
/*
* Cac hieu ung ve hinh anh + am thanh se duoc dinh nghia o day
*
*/

// CockRoach effects
void CockRoach::fUpdateDieImage()
{
	stopAllActions();

    CCArray* frames = CCArray::createWithCapacity(kNumberListDie);
    
    CCSpriteFrameCache* frameCache = CCSpriteFrameCache::sharedSpriteFrameCache();
    
    //nap 3 frame hinh vao frames
    char file[100] = {0};
	
    for (int i = kNumberListDie ; i > 0; i--)
    {
        sprintf(file, "%d.png", i);

		CCSpriteFrame* frame = frameCache->spriteFrameByName(file);

        frames->addObject(frame);
    }
    
    //tao animation tu frames
    CCAnimation* animation = CCAnimation::createWithSpriteFrames(frames, 0.01f);

    CCAnimate* animate = CCAnimate::create(animation);
    
	CCRepeat* repeat = CCRepeat::create(animate, 1);

	CCSequence* seq3_1 = CCSequence::create(repeat, NULL);

    CCSequence* seq3_2 = CCSequence::create( CCRotateTo::create(0.01f, fRotateAngle()), NULL);

	CCSpawn* spawn = CCSpawn::create(seq3_2, seq3_1, NULL);

	runAction(spawn);

	// Death effect
	setStatus(DEATH);

	fCockRoachDisappear();
}

void CockRoach::fCockRoachAppear()
{
	// Appear effect
	CCFadeIn *fade = CCFadeIn::create(1.f);

	runAction(fade);
}
void CockRoach::fCockRoachDisappear()
{
	// Rotate con gian
	CCFadeOut *fadeOut = CCFadeOut::create(1.f);

	runAction(CCSequence::createWithTwoActions(fadeOut, CCCallFuncO::create(fadeOut, callfuncO_selector(CockRoach::removeSelf), (CCObject*)this)));
	
}

void CockRoach::removeSelf(CCObject* sender){
	
	if (sender != NULL){
		//CCLOG("%s", "rmeove");
		CockRoach* cr = (CockRoach*)sender;
		cr->pauseSchedulerAndActions();
		if (cr->getParent() != NULL){
			cr->removeFromParent();
		}
		cr = NULL;
	}
}

void CockRoach::update(float delta)
{
	
	if(getPositionY() + boundingBox().size.height / 2 <= 0)
	{
		#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //Android
				JNIClass::vibrate(500);
		#endif
		pauseSchedulerAndActions();

		((HelloWorld*)getParent())->fUpdateUIImageLife((HelloWorld*)getParent());
		((HelloWorld*)getParent())->removeChild(this);
		this->removeFromParent();
	}
}